package controllers;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.regex.Pattern;

import models.User;
import models.Weixin;
import net.ufrog.common.utils.Files;
import net.ufrog.common.utils.Passwords;
import net.ufrog.common.utils.Strings;
import net.ufrog.common.utils.Strings.StringSet;
import play.i18n.Messages;
import play.libs.Images;
import play.libs.MimeTypes;
import play.mvc.Before;
import play.mvc.Controller;
import utils.Calendars;

/**
 * 管理控制器<br>
 * 权限控制，其他管理相关控制器需继承
 * 
 * @author ultrafrog
 * @version 1.0, 2014-11-04
 * @since 1.0
 */
public class Admin extends Controller {

	/** 权限控制 */
	@Before(unless = {"sign_in", "sign_out", "authenticate"})
	public static void authorize() {
		if (User.current() == null) {
			flash.error(Messages.get("admin.authorize.failure.user"));
			sign_in();
		} else if (!Strings.in(User.current().type, User.Type.ADMIN, User.Type.ROOT)) {
			flash.error(Messages.get("admin.authorize.failure.type"));
			sign_in();
		}
	}
	
	/** 索引 */
	public static void index() {
		//WXRequest.test(Weixin.current());
		renderArgs.put("user", User.current());
		renderArgs.put("weixin", Weixin.current());
		render();
	}
	
	/** 登录表单 */
	public static void sign_in() {
		render();
	}
	
	/**
	 * 身份认证
	 * 
	 * @param account
	 * @param password
	 */
	public static void authenticate(String account, String password) {
		// 初始化
		User user = null;
		
		// 判断并查询用户
		if (Strings.email(account)) user = User.find("byEmail", account).first();
		else if (Pattern.matches("1[3-8][0-9]{9}", account)) user = User.find("byCellphone", account).first();
		if (user == null) user = User.find("byNickname", account).first();
		
		// 判断用户
		if (user == null || !Passwords.match(password, user.password)) {
			flash.error(Messages.get("admin.authenticate.failure.user"));
			sign_in();
		} else if (!Strings.equals(user.status, User.Status.ENABLED)) {
			flash.error(Messages.get("admin.authenticate.failure.status"));
			sign_in();
		} else if (!Strings.in(user.type, User.Type.ADMIN, User.Type.ROOT)) {
			flash.error(Messages.get("admin.authenticate.failure.type"));
			sign_in();
		}
		
		// 用户符合条件进行处理
		User.currentId(user.id);
		index();
	}
	
	/** 充值密码表单 */
	public static void reset_password() {
		render();
	}
	
	/**
	 * 修改密码
	 * 
	 * @param opassword
	 * @param npassword
	 * @param cpassword
	 */
	public static void reset(String opassword, String npassword, String cpassword) {
		// 参数验证
		validation.required(opassword).message(Messages.get("admin.reset.password.failure.opassword.required"));
		validation.required(npassword).message(Messages.get("admin.reset.password.failure.npassword.required"));
		validation.equals(cpassword, npassword).message(Messages.get("admin.reset.password.failure.cpassword.equals"));
		if (validation.hasErrors()) {
			renderJSON(validation);
		}
		
		// 判断原密码是否正确
		User user = User.findById(User.currentId());
		if (!Passwords.match(opassword, user.password)) {
			validation.addError("opassword", Messages.get("admin.reset.password.failure.opassword.nomatch"));
			renderJSON(validation);
		}
		
		// 修改密码
		user.password = Passwords.encode(npassword);
		user.save();
		User.currentId(null);
		flash.success(Messages.get("admin.reset.password.success"));
		renderJSON(validation);
	}
	
	/** 注销 */
	public static void sign_out() {
		User.currentId(null);
		flash.success(Messages.get("admin.sign.out.success"));
		sign_in();
	}
	
	/**
	 * 保存文件
	 * 
	 * @param file
	 * @param accepts
	 */
	protected static models.File saveFile(File file, String... accepts) {
		return saveFile(file, null, null, accepts);
	}
	
	/**
	 * 保存文件
	 * 
	 * @param file
	 * @param width
	 * @param height
	 * @param accepts
	 * @return
	 */
	protected static models.File saveFile(File file, Integer width, Integer height, String... accepts) {
		// 验证扩展名
		String ext = Files.getExt(file.getName());
		if (!Strings.in(ext, accepts)) {
			throw new Error("");
		}
		
		// 初始化
		String mimeType = MimeTypes.getMimeType(file.getName());
		BigDecimal size = BigDecimal.valueOf(file.length()).divide(BigDecimal.valueOf(1024), 2, RoundingMode.HALF_EVEN);
		File dir = new File("public/upload/" + Calendars.format("yyyyMMdd"));
		
		// 保存文件
		dir.mkdirs();
		File dest = new File(dir, Calendars.format("yyyyMMddHHmmss") + Strings.random(4, StringSet.NUMERIC) + "." + ext);
		if (width != null || height != null) {
			Images.resize(file, dest, width, height, true);
		} else {
			play.libs.Files.copy(file, dest);
		}
		
		// 
		models.File f = new models.File(file.getName(), ext, mimeType, size, dest.getPath()).save();
		return f;
	}
}
